<template>
  <div class="h-all flex fd-c">
    <div class="fs-20 flex nodarg ra-10 mr10 ai-c">
      <Select pretext="年级：" @change="getDictation(1)" clear class="w-140 b-0 ai-c hand fs-15 h-35" :data="nianji" props="t,v" v-model="query.grade"></Select>
      <Select pretext="上下册：" @change="getDictation(1)" clear class="w-150 b-0 ai-c hand fs-15 ml10 h-35" :data="[{value:1,label:'上册'},{value:2,label:'下册'}]" v-model="query.volume"></Select>
      <Select @change="getDictation()" clear class="w-120 b-0 ai-c hand fs-15 ml10 h-35" pretext="个数：" :data="[5,6,7,8,9,10,11,12,13,14,15]" v-model="info.size"></Select>
      <div @click="startTimer(1)" class="pl15 pr15 pt5 pb6 nodarg hand bc-primary fc-fff ml15 fs-16 ra-100">开始听写 <span class="iconfont icon-bofang1"></span></div>
      <div @click="stopTimer" class="pl15 pr15 pt5 pb6 nodarg hand fc-999 ml5 fs-16 ra-100">重新听写</div>
      <span class="flex-1"></span>
      <span @click="info.isLess=true;" class="fc-aa nodarg hand fs-18">听写记录</span>
    </div>
    <div class="w-all mt10 flex-1 nodarg">
      <div v-if="!info.isOpen" class="flex ai-c h-all fd-c w-all jc-c">
        <div :class="{'flash-red':infotime.currentTime>20}" class="flex ai-c jc-c fd-c mb90 ra-30 glass-card pp50 w-500">
          <div class="flex w-all ai-c jc-b">
            <span class="fs-20">当前正在听写第 ( {{infotime.nextCount}} ) 个单词</span>
            <span class="fs-30 centers " v-html="formatTime(infotime.currentTime)"></span>
          </div>
          <input type="text" @input="changeCheck" v-model="info.wordText" spellcheck="false" style="border:2px solid #ff9900" class="h-80 centers fb fs-40 ra-100 mt10 bc-t w-all">
          <div class="flex ai-c w-all jc-b">
            <span class="fs-30 fc-FF4500">总用时<span v-html="formatTime(infotime.allTime)"></span></span>
            <div @click="startTimer()" class="pl20 pr20 pt15 pb15 nodarg hand bc-primary fc-fff mt10 fs-19 ra-100">下一词</div>
          </div>
        </div>
      </div>
      <div v-else class="w-all h-all">
        <div class="w-all pt10 pb10 pr15 flex fw ">
          <div v-for="item in info.list" style="width:350px;height: 280px;" class="flex pt10 fd-c mb10 ml10 pl20 ra-10 glass-card">
            <div class="fs-40 fc-FF4500 fb">{{item.word}}</div>
            <div @click="onWordPlay(item.word,0)" class="fs-23 mt10 hand nodarg flex ai-c fc-aa">英：{{item.en_pronunciation}} <span class="iconfont icon-ting fs-25 fc-pri"></span></div>
            <div @click="onWordPlay(item.word,1)" class="fs-23 mt5 hand nodarg flex ai-c fc-aa">美：{{item.us_pronunciation}} <span class="iconfont icon-ting fs-25 fc-pri"></span></div>
            <div class="fs-16 pr10" v-html="item.desc"></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <dig :isHeader="false" v-model="info.isLess">
    <div class="w-700 glass-card h-500">
      <table class="table w-all">
        <thead>
          <tr>
            <td>时间</td>
            <td>听写单词</td>
            <td>操作</td>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in info.lession">
            <td v-date>{{item.ctime}}</td>
            <td>{{item.words}}</td>
            <td><span @click="btnDel(item)" class="fc-danger nodarg hand pp10">删除</span></td>
          </tr>
        </tbody>
      </table>

      <div class="flex ai-c jc-e pr10">
        <page @change="getLesson" :size="info.size" :total="info.total" :page="info.page"></page>
      </div>
    </div>
  </dig>
</template>

<script setup lang='ts'>
import { ref, reactive, onUnmounted } from 'vue';
import yy from '@lib/mixin';
import useStore from '../../store';
const { ipcRenderer } = window.require('electron');


const nianji = [
  { t: '一年级', v: 1 },
  { t: '二年级', v: 2 },
  { t: '三年级', v: 3 },
  { t: '四年级', v: 4 },
  { t: '五年级', v: 5 },
  { t: '六年级', v: 6 },
  { t: '初一', v: 7 },
  { t: '初二', v: 8 },
  { t: '初三', v: 9 }
]
const st = useStore();

const query = reactive({
  grade: 3,
  unit: 1,
  volume: 1,
  page: 1,
  size: 10,
  serch: ''
})

function onWordPlay(word, type) {
  let src = `http://dict.youdao.com/dictvoice?type=${type}&audio=${word}`;
  if (info.playAudio) {
    info.playAudio.pause();
    info.playAudio = null;
  }

  info.playAudio = new Audio(src);
  info.playAudio.volume = 1;
  info.playAudio.play()
}

function btnDel(item) {
  yy.msg.confirm('确定要删除吗', res => {
    if (res == 'ok') {
      st.invoke('words', { sql: `delete from dictation where id=${item.id}` }).then(res => {
        if (res) {
          yy.msg.success('删除成功')
          getLesson();
        }
      })
    }
  })
}

const info = reactive({
  list: [],
  lession: [],
  playAudio: null,
  type: 0,
  isOpen: true,
  wordText: "",
  miss: [],
  size: 6,
  page: 1,
  total: 0,
  isLess: false
})

// 格式化时间显示 (HH:MM:SS.mmm)
function formatTime(timeInMs) {
  return `${Math.floor((timeInMs % 3600) / 60).toString().padStart(2, '0')}<i class='fs-12'>分</i>${(timeInMs % 60).toString().padStart(2, '0')}<i class='fs-12'>秒</i>`;
}

const infotime = reactive({
  isRunning: false,
  currentTime: 0,
  startTime: 0,
  time: null,
  usetime: 0,
  currUseTime: 0,
  allTime: 0,
  nextCount: 0,
  list: []
})
function getLesson(page) {
  if (page) info.page = page;
  st.invoke('sql', { table: 'dictation', where: '', page: info.page, size: info.size }).then(res => {
    info.total = res.total;
    info.lession = res.list || []
  })
}
getLesson()
function getDictation() {
  let sql = `SELECT dictionary.* FROM dictionary WHERE 1=1
  ${query.grade && (` and grade=${query.grade}`) || ''}
  ${query.volume && (` and volume=${query.volume}`) || ''} and 
  NOT EXISTS (SELECT 1 FROM dictation  WHERE CONCAT(',', dictation.words, ',') LIKE CONCAT('%,', dictionary.word, ',%')) order by unit asc limit ${info.size}`
  ipcRenderer.invoke('words', { sql }).then(res => {
    console.log(res, '========dictation');
    
    info.list = res || [];
  })
}
getDictation();
function startTimer(star) {
  let word = info.list[infotime.nextCount];
  infotime.nextCount++
  if (infotime.time) {
    clearInterval(infotime.time);
    infotime.time = null;
  }
  if (!word && infotime.nextCount) {
    clearInterval(infotime.time);
    infotime.time = null;
    infotime.isRunning = false;
    info.isOpen = true;
    saveDictation()
    return;
  }
  let i = 0;
  infotime.isRunning = true;
  info.isOpen = false;
  wordPlay(word.word, info.type ? 0 : 1);
  infotime.time = setInterval(() => {
    infotime.currentTime = i;
    infotime.allTime = infotime.currUseTime + i;
    i++
    if (!(i % 8)) {
      wordPlay(word.word, info.type ? 0 : 1);
    }
    if (i == 30) {
      infotime.currUseTime = infotime.currUseTime + i;
      info.miss.push(word.word)
      startTimer()
    }
  }, 1000)
}

function stopTimer() {
  clearInterval(infotime.time);
  info.miss = [];
  info.isOpen = true;
  infotime.allTime = 0;
  infotime.nextCount = 0;
  infotime.currentTime = 0;
  infotime.currUseTime = 0;
  infotime.time = null;
  yy.msg.success('重置成功')
}

function wordPlay(word, type) {
  info.type = type;
  let src = `http://dict.youdao.com/dictvoice?type=${type}&audio=${word}`;
  if (info.playAudio) {
    info.playAudio.pause();
    info.playAudio = null;
  }

  info.playAudio = new Audio(src);
  info.playAudio.volume = 1;
  info.playAudio.play()
}

function changeCheck(e) {
  let { value } = e.target as HTMLInputElement;
  let word = info.list[infotime.nextCount - 1];
  if (value == word.word) {
    info.wordText = "";
    startTimer();
  }
}
// can,and,eye,arm,ear
function saveDictation() {
  let sql = `insert into dictation (ctime,words,miss,utime,remark) values ('${Date.now()}','${info.list.map(v => v.word).toString()}','${info.miss.toString()}',${infotime.allTime},'')`;
  st.sql({ sql }).then(res => {
    yy.msg.success('单词听写完成');
    info.miss = [];
  })
}

onUnmounted(() => {
  if (infotime.time) {
    clearInterval(infotime.time);
    infotime.time = null;
  }
})

</script>

<style lang='less'>
.b-0 {
  border: 0;
}

.table {
  font-weight: 300;
  border-collapse: separate !important;
  border-spacing: 0px !important;
  thead {
    tr {
      box-shadow: 0 0px 30px rgba(0, 0, 0, 0.1);
      background: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);
    }
  }
  thead tr td {
    padding: 15px 10px;
    background-color: ;
    font-size: 18px;
    color: #333;
    
  }
  tbody tr td {
    padding: 15px 10px;
    font-size: 18px;
    border-bottom: 1px solid #f2f2f2;
  }
  tbody tr {
    color: #555;
    &:hover {
      cursor: pointer;
      background-color: #fdfdfd;
    }
    &:last-child td {
      border-bottom: 0 solid #f8f8f8;
    }
  }
}

/* 红框闪烁 + 阴影动画 */
.flash-red {
  animation: flash 0.5s infinite alternate;
}

@keyframes flash {
  from {
    border-color: transparent;
    box-shadow: 0 0 0 rgba(255, 0, 0, 0);
  }
  to {
    border-color: #ff0000;
    box-shadow: 0 0 15px rgba(255, 0, 0, 0.8);
  }
}
</style>